package com.example.demo111111.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.List;

@RestController
public class FileController {
    @Value("${server.port:8080}")  // 默认 8080
    private String serverPort;

    private static String host;
    @PostConstruct
    public void init() {
        host = getLocalHostAddress() + ":" + serverPort + "/upload/";
    }

    public static String getHost() {
        return host;
    }

    // 获取本机IP地址
    private static String getLocalHostAddress() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            return localHost.getHostAddress(); // 返回IP地址（如 192.168.1.100）
        } catch (UnknownHostException e) {
            return "localhost"; // 失败时回退到localhost
        }
    }

//    public static final String host = getLocalHostAddress()+":"+8080+"/upload/";
    private static final String filePath = System.getProperty("user.dir")+"/file/";

    //上传
    @PostMapping(value = "/upload")
    @ResponseBody
    public String upload(MultipartFile file) {
        String flag = System.currentTimeMillis() + "";//取了一个时间戳
        String fileName = file.getOriginalFilename();//获取上传文件的原始文件
        String image = null;
        try {
            if (FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);
            image = "http://"+host + flag + "-" + fileName;
            System.out.println(fileName + "--上传成功");
        } catch (Exception e) {
            System.out.println(fileName + "--上传失败");
        }


        return image;
    }


    //下载
    @GetMapping(value = "/download/{flag}")
    public void download(@PathVariable String flag, HttpServletResponse response) {
        if(!FileUtil.isDirectory(filePath)){
            FileUtil.mkdir(filePath);
        }

        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(filePath);

        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");

        try{
            if(StrUtil.isNotEmpty(avatar)){
                response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + avatar);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }

        } catch (Exception e) {
            System.out.println("文件下载失败");
        }

    }
}
